package com.xayy.health.ds.service.impl;

import cn.kawins.base.result.CheckResult;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;
import com.xtck.ha.common.core.annotation.SortKey;
import com.xtck.ha.common.core.domain.R;
import com.xtck.ha.common.core.utils.PageUtils;
import com.xtck.ha.common.core.web.service.dsimpl.BaseServiceImpl;
import com.xtck.ha.common.core.config.DsServerConfig;
import com.xtck.ha.common.core.utils.DomainUtils;
import com.xayy.health.ds.model.DsTaskInfo;
import com.xayy.health.ds.service.DsTaskInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description: DsTaskInfoService实现类
 * @Auther:liuyuan
 * @Date:2025-07-08
 */
@Slf4j
@Service
public class DsTaskInfoServiceImpl extends BaseServiceImpl<DsTaskInfo> implements DsTaskInfoService {
  /**
  *
  * 冗余代码，为自定义开发DS-Server接口服务
  *
  */
   private static String TABLE_NAME = "TB_TASK_INFO";
   private String getUrl(){
      return getDsServerConfig().getUrl();
   }

   public List<DsTaskInfo> selectDsTaskInfoList(DsTaskInfo dsTaskInfo){
       Page page = PageUtils.getLocalPage();

       RestTemplate restTemplate = new RestTemplate();
       Map<String, Object> map = DomainUtils.objectToMapForQuery(dsTaskInfo);
       JSONObject jo = new JSONObject();
       if (!map.isEmpty()){
           if (map.size()>1){
               List list = new ArrayList();
               map.forEach((k,v)->{
                   JSONObject pa = new JSONObject();
                   JSONObject like = new JSONObject();
                   if (k.equals("NAME")){
                       like.put("$like","%"+v+"%");
                       pa.put(k,like);
                   }else
                       pa.put(k,v);
                   list.add(pa);
               });
               jo.put("$and",list);
           }else {
               jo.putAll(map);
           }
       }
       UriComponentsBuilder ucb = UriComponentsBuilder.fromHttpUrl(geturl());
       if(!map.isEmpty()){
           ucb = ucb.queryParam("filter", jo.toJSONString());
       }
       if (page!=null){
           ucb = ucb.queryParam("page",page.getPageNum())
                   .queryParam("pagesize",page.getPageSize());
       }

       // 新增排序
       if (entityClass.isAnnotationPresent(SortKey.class)){
           String value = this.entityClass.getAnnotation(SortKey.class).value();
           ucb = ucb.queryParam("sort", value);
       }

       URI uri = ucb.build().toUri();
       // 设置请求头，特别是Authorization头部来携带token
       HttpHeaders headers = new HttpHeaders();
       headers.add("Ds-Route-key", this.getDsRouteKey());
       // 不需要传递body对于GET请求来说，除非你需要传递JSON等格式的参数体，但通常不这么做。
       HttpEntity<String> entity = new HttpEntity<>(headers);
       // 执行GET请求并处理响应
       R response = restTemplate.exchange(uri, HttpMethod.GET, entity, R.class).getBody();
//        log.info("Response with params: {}",response.getData());
       PageUtils.clearPage();
       List<DsTaskInfo> list = new ArrayList<>();
       if (R.isSuccess(response)) {
           Object data1 = response.getData();
           if (data1 != null) {
               JSONArray arrays = com.alibaba.fastjson2.JSON.parseArray(JSON.toJSONString(data1));
               list = arrays.stream().map(o -> {
                   try {
                       return JSONObject.parseObject(JSONObject.toJSONString(o), this.getEntityClass());
                   } catch (Exception e) {
                       throw new RuntimeException(e);
                   }
               }).collect(Collectors.toList());
           }
       }
       return list;
   }


    /**
     * 根据任务id查询任务数据
     *
     * @param taskId 任务id
     * @return CheckResult<TaskInfo>
     */
    @Override
    public CheckResult<DsTaskInfo> selectTaskInfo(Long taskId) {
        if (taskId != null) {
            return CheckResult.success(selectTById(taskId));
        } else {
            return CheckResult.fail("任务id不能为空");
        }
    }

    @Override
    public List<DsTaskInfo> selectByExample(DsTaskInfo dsTaskInfo){
        String sql = "select * from HEALTH.TB_TASK_INFO t WHERE 1=1 " +
                "AND t.satellite_code = " +
                "'" +dsTaskInfo.getSatelliteCode()+"'"+
                " AND t.json_params like " +
                "'%" +dsTaskInfo.getJsonParams()+"%'"+
                " AND t.type like " +
                "'%" +dsTaskInfo.getType()+"%'"+
                " ORDER BY start_time desc";
        return selectBySql(sql);
    }

    @Override
    /**
     * 批量更新状态
     *
     * @param taskId 任务id
     */
    public void updateBatchStatus(List<Long> taskId){
        String sql = "UPDATE HEALTH.tb_task_info t SET t.status = 0 WHERE t.id in\n (";
        for (long id : taskId){
            sql += id+",";
        }
        if (sql.endsWith(",")) {
            sql = sql.substring(0, sql.length() - 1);
        }
        sql += ");";
        selectBySql(sql);
    }

    @Override
    public List<DsTaskInfo> selectByIds(List<Long> taskIds){
        String sql = "SELECT * FROM HEALTH.tb_task_info t  WHERE t.id in\n (";
        for (long id : taskIds){
            sql += id+",";
        }
        if (sql.endsWith(",")) {
            sql = sql.substring(0, sql.length() - 1);
        }
        sql += ");";
        return selectBySql(sql);
    }

    @Override
    public void deleteCalculateData(List<Long> predictIdList){
        String sql = "DELETE from HEALTH.tb_calculate_data WHERE task_id in\n (";
        for (long id : predictIdList){
            sql += id+",";
        }
        if (sql.endsWith(",")) {
            sql = sql.substring(0, sql.length() - 1);
        }
        sql += ");";
        selectBySql(sql);
    }
}
